package com.qin.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.qin.dao.BookCategoryDao;
import com.qin.entity.BookCategory;
import com.qin.service.BookCategoryService;

import cn.hutool.log.StaticLog;

public class BookCategoryServiceImpl implements BookCategoryService {

	private BookCategoryDao bookCategoryDao = new BookCategoryDao();
	
	@Override
	public Long insertBookCategory(BookCategory bookCategory) {
		return bookCategoryDao.insertBookCategory(bookCategory);
	}

	@Override
	public int deleteBookCategory(Long id) {
		return bookCategoryDao.logicDeleteBookCategory(id);
	}

	@Override
	public int updateBookCategory(Long id, BookCategory bookCategory) {
		return bookCategoryDao.updateBookCategory(id, bookCategory);
	}

	@Override
	public BookCategory getBookCategoryById(Long id) {
		return bookCategoryDao.queryBookCategoryById(id);
	}

	@Override
	public List<BookCategory> getAllBookCategories() {
		return bookCategoryDao.queryAllBookCategory();
	}

	@Override
	public List<BookCategory> queryBookCategoryByPId(Long id) {
		return bookCategoryDao.queryBookCategoryByPId(id);
	}

	@Override
	public List<BookCategory> getBookCategoryToLevel() {
		return getBookCategoryToLevel(getAllBookCategories());
	}
	
	@Override
	public List<BookCategory> getBookCategoryToLevel(List<BookCategory> bookCategories) {
		StaticLog.debug("getBookCategoryToLevel（）方法被调用，按照等级生成树结构");
		if(bookCategories == null) {
			return null;
		}
		
		List<BookCategory> collect = bookCategories.stream().filter(bookCategory->
			bookCategory.getParentId() == null
		).map(bookCategory->
			setBookCategoryChildren(bookCategory)
		).collect(Collectors.toList());
		
		return collect;
	}
	
	/**
	 * 递归设置图书分类的子级分类
	 * @param bookCategory 要形成树结构的根节点
	 * @return 树结构的图书分类
	 */
	public BookCategory setBookCategoryChildren(BookCategory bookCategory) {
		Long id = bookCategory.getId();
		
		List<BookCategory> chidren = bookCategoryDao.queryBookCategoryByPId(id);
		
		if(chidren != null) {
			// 递归设置
			List<BookCategory> collect = chidren.stream()
					.map(category->setBookCategoryChildren(category))
					.collect(Collectors.toList());
			
			bookCategory.setChildren(collect);
		}else {
			bookCategory.setChildren(chidren);
		}
		
		return bookCategory;
	}

	@Override
	public List<BookCategory> queryBookCategoryByCLevel(Integer level) {
		StaticLog.debug("queryBookCategoryByCLevel（）调用，按照级别【{}】查询所有图书", level);
		return bookCategoryDao.queryBookCategoryByCLevel(level);
	}

	
	
}
